package org.totoro.lock;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author YHL
 * @version V1.0
 * @Description:
 * @date 2018-12-05
 */
public class Test1 {


    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, e -> {
            countDownLatch.countDown();
        });

        countDownLatch.await();

        String path = "/lock";

        Stat exists = zooKeeper.exists(path, false);

        if (exists != null) {
            zooKeeper.delete(path, exists.getVersion());
        }

        String s = zooKeeper.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

//
        System.out.println(s);


        for (int i = 0; i < 10; i++) {

            String s1 = zooKeeper.create(path+"/" , null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);

            System.out.println(s1);

            zooKeeper.exists(s1,o ->{
                System.out.println("监听到回调");
            });
        }


        List<String> children = zooKeeper.getChildren(path, false);

        List<String> collect = children.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());
        for (String child : collect) {
            System.out.println(child);
        }

//

        Thread.sleep(10_0000);
    }

}
